package com.ch999.comparedata.hander;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.ch999.comparedata.entity.SQLUndoLog;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

public class DeleteHandler extends AbstractHandler {

    private Delete delete;

    public DeleteHandler(Statement statement, DataSource dataSource, String dataSourceType) {
        super(statement, dataSource,dataSourceType);
        delete = (Delete) statement;
    }


    /**
     * 执行前 组装数据
     */
    @Override
    public void preHandle() throws Throwable {
        String executeSql = String.format(getExecuteSql(dataSourceType),delete.getTable().getName(),delete.getWhere().toString());
        List<Entity> result = Db.use(dataSource).query(executeSql);

        for (Entity entity:result){
            StringBuffer col = new StringBuffer();
            StringBuffer values = new StringBuffer();
            for(Map.Entry<String, Object> obj:entity.entrySet()){
                if (StringUtils.isEmpty(obj.getValue())){
                    continue;
                }
                col.append(obj.getKey()).append(",");
                if (obj.getValue().getClass().getTypeName().equals("java.lang.String")){
                    values.append("'").append(obj.getValue()).append("'").append(",");
                }else {
                    values.append(obj.getValue()).append(",");
                }
            }
            col.deleteCharAt(col.length()-1);
            values.deleteCharAt(values.length()-1);
            String resetSql = String.format(insertSql,delete.getTable().getName(),col.toString(),values.toString());
            SQLUndoLog sqlUndoLog = new SQLUndoLog();
            sqlUndoLog.setSqlCommandType(SqlCommandType.DELETE);
            sqlUndoLog.setTableName(delete.getTable().getName());
            sqlUndoLog.setBeforeImage(entity);
            //保存日志
            addUndoLog(sqlUndoLog,resetSql);
        }
    }

    /**
     * 执行后
     */
    @Override
    public void postHandle() {

    }
}
